/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.fjs.liyq.service.impl;

import edu.fjs.liyq.dao.OrderDao;
import edu.fjs.liyq.dao.impl.OrderDaoImpl;
import edu.fjs.liyq.entity.Cart;
import edu.fjs.liyq.entity.CartItem;
import edu.fjs.liyq.entity.Order;
import edu.fjs.liyq.entity.OrderDetail;
import edu.fjs.liyq.service.OrderService;
import edu.fjs.liyq.service.ProductService;
import edu.fjs.liyq.util.DBUtil;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author danny
 */
public class OrderServiceImpl implements OrderService {

    OrderDao orderDao = new OrderDaoImpl();
    ProductService productService = new ProductServiceImpl();

    @Override
    public boolean placeOrder(Cart cart) {
        boolean result = false;

        // 获取Connection，并开启事务
        Connection con = DBUtil.getConnection();
        try {
            con.setAutoCommit(false);
        } catch (SQLException ex) {
            Logger.getLogger(OrderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {
            // 写入订单主表
            //构造Order实例
            Order order = new Order(Long.MIN_VALUE, cart.getUser().getAccount(), new Date(System.currentTimeMillis()), cart.getCost(), 1, 1);
            orderDao.insertOrder(order);

            // 遍历购物车明细，插入订单详表
            for (CartItem item : cart.getItems()) {
                //查询商品库存
                int checkStock = productService.checkStock(item.getProduct().getEpId(), item.getQuantity());
                //更新商品库存
                if (checkStock >= 0) {
                    productService.decreaseStock(item.getProduct().getEpId(), item.getQuantity());
                    //构造OrderDetail对象
                    OrderDetail od = new OrderDetail(Long.MIN_VALUE, order.getEoId(), item.getProduct().getEpId(), item.getQuantity(), item.getCost());
                    //            插入OrderDetail对象
                    orderDao.insertOrderDetail(od);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                con.rollback();
            } catch (SQLException ex) {
                Logger.getLogger(OrderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            }
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException ex) {
                    Logger.getLogger(OrderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        return true;
    }

}
